//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysPostMapper postMapper;
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysUserPostMapper userPostMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    protected Validator validator;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TokenService tokenService;

    public SysUserServiceImpl() {
    }

    public List<SysUser> selectUserList(SysUser user) {
        if (StringUtils.isBlank(user.getOrgNo())) {
            user.setOrgNo(this.tokenService.getLoginUser().getSysUser().getOrgNo());
        }

        return this.userMapper.selectUserList(user);
    }

    public List<SysUser> selectAllocatedList(SysUser user) {
        if (StringUtils.isBlank(user.getOrgNo())) {
            user.setOrgNo(this.tokenService.getLoginUser().getSysUser().getOrgNo());
        }

        return this.userMapper.selectAllocatedList(user);
    }

    public List<SysUser> selectUnallocatedList(SysUser user) {
        if (StringUtils.isBlank(user.getOrgNo())) {
            user.setOrgNo(this.tokenService.getLoginUser().getSysUser().getOrgNo());
        }

        return this.userMapper.selectUnallocatedList(user);
    }

    public SysUser selectUserByUserName(String userName) {
        return this.userMapper.selectUserByUserName(userName);
    }

    public SysUser selectUserById(Long userId) {
        SysUser user = this.userMapper.selectUserById(userId);
        if (user.getPasswordUpdateTime() == null) {
            user.setIsExpired("0");
        } else {
            String passwordExpireTime = (String)this.redisService.getCacheObject("sys_config:password.expire.time");
            Long time = Long.parseLong(passwordExpireTime) * 24L * 60L * 60L * 1000L;
            if (System.currentTimeMillis() > time + user.getPasswordUpdateTime().getTime()) {
                user.setIsExpired("1");
            }
        }

        return user;
    }

    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = this.roleMapper.selectRolesByUserName(userName);
        return CollectionUtils.isEmpty(list) ? "" : (String)list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    public String selectUserPostGroup(String userName) {
        List<SysPost> list = this.postMapper.selectPostsByUserName(userName);
        return CollectionUtils.isEmpty(list) ? "" : (String)list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    public String checkUserNameUnique(String userName) {
        int count = this.userMapper.checkUserNameUnique(userName);
        return count > 0 ? "1" : "0";
    }

    public String checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = this.userMapper.checkPhoneUnique(user.getPhonenumber());
        return StringUtils.isNotNull(info) && info.getUserId() != userId ? "1" : "0";
    }

    public String checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = this.userMapper.checkEmailUnique(user.getEmail());
        return StringUtils.isNotNull(info) && info.getUserId() != userId ? "1" : "0";
    }

    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = ((SysUserServiceImpl)SpringUtils.getAopProxy(this)).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }

    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int insertUser(SysUser user) {
        int rows = this.userMapper.insertUser(user);
        this.insertUserPost(user);
        this.insertUserRole(user);
        return rows;
    }

    public boolean registerUser(SysUser user) {
        return this.userMapper.insertUser(user) > 0;
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        this.userRoleMapper.deleteUserRoleByUserId(userId);
        this.insertUserRole(user);
        this.userPostMapper.deleteUserPostByUserId(userId);
        this.insertUserPost(user);
        return this.userMapper.updateUser2(user);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public void insertUserAuth(Long userId, Long[] roleIds) {
        this.userRoleMapper.deleteUserRoleByUserId(userId);
        this.insertUserRole(userId, roleIds);
    }

    public int updateUserStatus(SysUser user) {
        return this.userMapper.updateUser(user);
    }

    public int updateUserProfile(SysUser user) {
        return this.userMapper.updateUser(user);
    }

    public boolean updateUserAvatar(String userName, String avatar) {
        return this.userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    public int resetPwd(SysUser user) {
        return this.userMapper.updateUser(user);
    }

    public int resetUserPwd(String userName, String password) {
        return this.userMapper.resetUserPwd(userName, password);
    }

    public void insertUserRole(SysUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            List<SysUserRole> list = new ArrayList();
            Long[] var4 = roles;
            int var5 = roles.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Long roleId = var4[var6];
                SysUserRole ur = new SysUserRole();
                ur.setUserId(user.getUserId());
                ur.setRoleId(roleId);
                list.add(ur);
            }

            if (list.size() > 0) {
                this.userRoleMapper.batchUserRole(list);
            }
        }

    }

    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            List<SysUserPost> list = new ArrayList();
            Long[] var4 = posts;
            int var5 = posts.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Long postId = var4[var6];
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }

            if (list.size() > 0) {
                this.userPostMapper.batchUserPost(list);
            }
        }

    }

    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds)) {
            List<SysUserRole> list = new ArrayList();
            Long[] var4 = roleIds;
            int var5 = roleIds.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Long roleId = var4[var6];
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }

            if (list.size() > 0) {
                this.userRoleMapper.batchUserRole(list);
            }
        }

    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int deleteUserById(Long userId) {
        this.userRoleMapper.deleteUserRoleByUserId(userId);
        this.userPostMapper.deleteUserPostByUserId(userId);
        return this.userMapper.deleteUserById(userId);
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int deleteUserByIds(Long[] userIds) {
        Long[] var2 = userIds;
        int var3 = userIds.length;

        for(int var4 = 0; var4 < var3; ++var4) {
            Long userId = var2[var4];
            this.checkUserAllowed(new SysUser(userId));
            this.checkUserDataScope(userId);
        }

        this.userRoleMapper.deleteUserRole(userIds);
        this.userPostMapper.deleteUserPost(userIds);
        return this.userMapper.deleteUserByIds(userIds);
    }

    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (!StringUtils.isNull(userList) && userList.size() != 0) {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder successMsg = new StringBuilder();
            StringBuilder failureMsg = new StringBuilder();
            String password = this.configService.selectConfigByKey("sys.user.initPassword");
            Iterator var9 = userList.iterator();

            while(var9.hasNext()) {
                SysUser user = (SysUser)var9.next();

                try {
                    SysUser u = this.userMapper.selectUserByUserName(user.getUserName());
                    if (StringUtils.isNull(u)) {
                        BeanValidators.validateWithException(this.validator, user, new Class[0]);
                        user.setPassword(SecurityUtils.encryptPassword(password));
                        user.setCreateBy(operName);
                        this.insertUser(user);
                        ++successNum;
                        successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                    } else if (isUpdateSupport) {
                        BeanValidators.validateWithException(this.validator, user, new Class[0]);
                        user.setUpdateBy(operName);
                        this.updateUser(user);
                        ++successNum;
                        successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                    } else {
                        ++failureNum;
                        failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                    }
                } catch (Exception var13) {
                    ++failureNum;
                    String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                    failureMsg.append(msg + var13.getMessage());
                    log.error(msg, var13);
                }
            }

            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                return successMsg.toString();
            }
        } else {
            throw new ServiceException("导入用户数据不能为空！");
        }
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public int editUserInfo(SysUser sysUser) {
        sysUser.setUpdateBy(SecurityUtils.getUsername());
        sysUser.setUpdateTime(DateUtils.getNowDate());
        return this.userMapper.updateUser(sysUser);
    }

    public AjaxResult editPwd(SysUser user) {
        SysUser sysUser = this.userMapper.selectUserById(user.getUserId());
        if (SecurityUtils.matchesPassword(user.getOldPassword(), SecurityUtils.encryptPassword(user.getPassword()))) {
            return AjaxResult.error("原密码和新密码不能相同");
        } else if (!SecurityUtils.matchesPassword(user.getOldPassword(), sysUser.getPassword())) {
            return AjaxResult.error("原密码错误，请重试");
        } else {
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            user.setUpdateBy(SecurityUtils.getUsername());
            user.setUpdateTime(DateUtils.getNowDate());
            user.setPasswordUpdateTime(DateUtils.getNowDate());
            int i = this.userMapper.updateUser(user);
            return i > 0 ? AjaxResult.success() : AjaxResult.error("修改密码失败");
        }
    }

    @Transactional(
            rollbackFor = {Exception.class}
    )
    public AjaxResult editLockStatus(SysUser user) {
        user.setUpdateTime(DateUtils.getNowDate());
        user.setIsLock("0");
        user.setPasswordFaultCount("0");
        int var = this.userMapper.updateUser(user);
        return var > 0 ? AjaxResult.success() : AjaxResult.error("更新数据失败");
    }

    public int updateUser1(SysUser user) {
        return this.userMapper.updateUser1(user);
    }
}
